package net.oschina.simpleplus.cnf.jwt;

import java.security.Key;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import javax.crypto.spec.SecretKeySpec;

import org.apache.shiro.codec.Base64;
import org.springframework.context.annotation.Configuration;

import com.alibaba.fastjson.JSON;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import net.oschina.simpleplus.util.TimeUtils;
import net.oschina.simpleplus.vo.UserVo;

@Configuration
public class JwtCnf {
	
	private SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
	private byte[]apiKeySecretBytes = Base64.encode("1111".getBytes());
	private long TTLMillis = TimeUnit.HOURS.toMillis(6);

	public String createJwtoken(UserVo userVo){
		long now = TimeUtils.currentTimeMillis();
		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());  
        //添加构成JWT的参数  
       JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")  
                                       .setSubject(JSON.toJSONString(userVo))
                                      .setIssuer(userVo.getEmail())  
                                      .setAudience(userVo.getEmail())  
                                      .signWith(signatureAlgorithm, signingKey);  
       //添加Token过期时间  
      if (TTLMillis >= 0) {  
          builder.setExpiration(new Date(now + TTLMillis)).setNotBefore(new Date(now));  
      }
      return builder.compact();
	}
	
	public UserVo parserJwt(String jwt){
		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());  
       return JSON.parseObject(Jwts.parser()
    	          .setSigningKey(signingKey)
    	          .parseClaimsJws(jwt).getBody().getSubject(), UserVo.class);
	}
}
